package org.anderground.editor.gui.menubar;

import static org.anderground.core.Logger.i;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.anderground.editor.gui.MainWindow;
import org.anderground.editor.model.EditorModel;

/**
 * 
 * @author Ilya Shurigyn
 * 
 */
@SuppressWarnings("serial")
public class OpenFileMenuItem extends JMenuItem {

	public OpenFileMenuItem(final MainWindow parent) {
		super("Open map");
		addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (MainWindow.modelChangedAfterLastSave)
					if (MainWindow
							.askForSave(
									"Do you want to open new file without saving current?",
									parent) != JOptionPane.CANCEL_OPTION)
						;
				showOpenFileDialog(OpenFileMenuItem.this);

				// should be called to centrate map
				parent.getMainPanel().getFirstView().afterPanelInit();
				parent.getMainPanel().getSecondView().afterPanelInit();

			}

		});
	}

	/**
	 * only standard xml files can be opened; other formats can be imported, but
	 * not "opened";
	 * 
	 * @param parent
	 *            - parent window
	 */
	public static void showOpenFileDialog(Component parent) {
		JFileChooser fc = new JFileChooser();
		FileFilter ff = new FileNameExtensionFilter("Standard Andergound file",
				new String[] { "xml" });
		fc.addChoosableFileFilter(ff);

		if (fc.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
			File f = fc.getSelectedFile();
			i("selected file: " + f.getName());
			EditorModel.getInstance().load(f.getAbsolutePath());
			MainWindow.modelChangedAfterLastSave = false;
		}

	}
}
